package com.yang.strategy.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.yang.constants.RedisConstants.CACHE_NULL_TTL;


@Service("queryWithPassThrough")
public class QueryWithPassThrough extends AbstractCacheStrategyImpl{

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public <R, ID> R getCache(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        //1.拿到前缀和ID拼接出key
        String key = keyPrefix + id;

        //2.根据key去查询redis
        String valueJson = stringRedisTemplate.opsForValue().get(key);

        //3.缓存命中，直接返回
        if (StrUtil.isNotBlank(valueJson)){
            return JSONUtil.toBean(valueJson,type);
        }

        //4.缓存未命中，去查询数据库
        R data = dbFallback.apply(id);

        //5.数据库没命中，写入redis，返回
        if (data == null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }

        //6.数据库命中，写入redis，返回
        super.setCache(key,data,time,unit,false);

        return data;
    }
}
